package com.landeb.shop.huo.frag;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.bean.BeanFragDetail;
import com.landeb.shop.huo.eventMsg.MsgResetGoodsFrag;
import com.landeb.shop.huo.httpRequest.FragDetailRequest;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class DetailFragActGoodDetail extends Fragment implements OnClickListener {

    private static final String BASE_URL = "baseUrl";
    private String mBaseUrl;
    private String mID;
    private String mDetailHtml;
    private String mParamHtml;
    private String mServiceHtml;
    private String mWebBaseUrl;

    private View view;
    private SwipeRefreshLayout mRSL;
    private Button btnParam, btnAfterService, btnDetail;
    private WebView mWebView;

    private String mUrl;
    private Retrofit mRetrofit;
    private FragDetailRequest mRequest;

    public static DetailFragActGoodDetail newInstance(String baseUrl) {
        DetailFragActGoodDetail fragment = new DetailFragActGoodDetail();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    public static DetailFragActGoodDetail newInstance(String baseUrl, String id) {
        DetailFragActGoodDetail fragment = new DetailFragActGoodDetail();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReset(MsgResetGoodsFrag event) {

        Log.e("onReset: ", "xxxxxxxxxxxxxxxxxxxxx");

        mID = event.getMid();

        refresh();
    }

    ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);


        mBaseUrl = getArguments().getString(BASE_URL);
        mID = getArguments().getString("id");

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(FragDetailRequest.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_detail_frag_act_good_detail, container, false);

        initView();
        initData();
        initEvent();

        refresh();
        return view;
    }

    private void initEvent() {

        mRSL.setEnabled(false);
        mRSL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        mRSL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                // TODO: 2016/11/19 下拉刷新
                mRSL.setRefreshing(false);
            }
        });

        btnAfterService.setOnClickListener(this);
        btnParam.setOnClickListener(this);
        btnDetail.setOnClickListener(this);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
    }


    private void initData() {

    }

    private void initView() {

        mRSL = (SwipeRefreshLayout) view.findViewById(R.id.frag_detail_srl);

        btnDetail = (Button) view.findViewById(R.id.frag_detail_btn_detail);
        btnParam = (Button) view.findViewById(R.id.frag_detail_btn_param);
        btnAfterService = (Button) view.findViewById(R.id.frag_detail_btn_afterService);

        mWebView = (WebView) view.findViewById(R.id.frag_detail_wv);
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.frag_detail_btn_detail:
// TODO: 2016/11/19 点击图文详情
                btnDetail.setTextColor(getResources().getColor(R.color.colorAccent));
                btnAfterService.setTextColor(getResources().getColor(R.color.black_overlay));
                btnParam.setTextColor(getResources().getColor(R.color.black_overlay));


                if (mDetailHtml == null) {
                    return;
                }

                Log.e("onClick:++++++++++++ ", mDetailHtml);

                mWebView.loadDataWithBaseURL(mWebBaseUrl, mDetailHtml, "text/html", "utf-8", null);

//                mWebView.loadUrl("www.baidu.com");

                break;

            case R.id.frag_detail_btn_param:
// TODO: 2016/11/19 点击规格参数
                btnParam.setTextColor(getResources().getColor(R.color.colorAccent));
                btnAfterService.setTextColor(getResources().getColor(R.color.black_overlay));
                btnDetail.setTextColor(getResources().getColor(R.color.black_overlay));


                if (TextUtils.isEmpty(mParamHtml)) {
//                    Toast.makeText(getActivity(),"mParamHtml",Toast.LENGTH_SHORT).show();
                    return;
                }

                mWebView.loadDataWithBaseURL(mWebBaseUrl, mParamHtml, "text/html", "utf-8", null);

                break;

            case R.id.frag_detail_btn_afterService:
// TODO: 2016/11/19 点击售后服务

                btnAfterService.setTextColor(getResources().getColor(R.color.colorAccent));
                btnDetail.setTextColor(getResources().getColor(R.color.black_overlay));
                btnParam.setTextColor(getResources().getColor(R.color.black_overlay));


                if (TextUtils.isEmpty(mServiceHtml)) {
//                    Toast.makeText(getActivity(),"mServiceHtml",Toast.LENGTH_SHORT).show();
                    return;
                }

                mWebView.loadDataWithBaseURL(mWebBaseUrl, mServiceHtml, "text/html", "utf-8", null);

                break;


        }

    }

    private void refresh() {

        mRequest.getDetailHTML(mID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanFragDetail>() {
                    @Override
                    public void onCompleted() {
                        Log.e("getDetailHTML", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("getDetailHTML", "onError: " + e.toString());

                    }

                    @Override
                    public void onNext(BeanFragDetail beanFragDetail) {

                        if (beanFragDetail.getStatus() == 1) {

                            mWebBaseUrl = beanFragDetail.getData().getBase();

                            mDetailHtml = beanFragDetail.getData().getContent();
                            mParamHtml = beanFragDetail.getData().getParam();
                            mServiceHtml = beanFragDetail.getData().getOther();

                            btnDetail.performClick();


                        } else {
                            Toast.makeText(getActivity(), beanFragDetail.getInfo(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });

    }

//    @Override
//    public void onStart() {
//        super.onStart();
//        EventBus.getDefault().register(this);
//    }

//    @Override
//    public void onStop() {
//        super.onStop();
//    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
